package plugin

import (
	"context"
	"fmt"
	"net/http"
	"net/url"
	"path"
	"strings"
	"time"

	influxdbModels "github.com/ssk9/obs/pkg/influxdb/models"

	_ "github.com/influxdata/influxdb1-client" // this is important because of the bug in go mod
	influxdbClientSDK "github.com/influxdata/influxdb1-client/v2"
)

func (d *Datasource) CollectOBSStorageInfo() error {
	obsCli := d.obsCli
	if obsCli == nil {
		return fmt.Errorf("no client")
	}

	info, err := obsCli.GetStorageInfo("grafana")
	if err != nil {
		d.logger.Error("GetStorageInfo", "err", err)
		return err
	}

	err = writeBySDK(d.influxdbCli, info.ObjectNumber)
	if err != nil {
		d.logger.Error("writeBySDK", err)
		return err
	}
	/* d.logger.Info("GetStorageInfo 🌟🌟🌟", info.ObjectNumber, info.Size)

	// save to GeminiDB influx
	rawQueryTpl := "demo,name=object_number num=%d %d"
	rawQuery := fmt.Sprintf(rawQueryTpl, info.ObjectNumber, time.Now().UnixNano())
	d.logger.Info("rawQuery 🌟🌟🌟", rawQuery) */

	/* req, err := createWriteRequest(ctx, d.dsInfo, rawQuery)
	if err != nil {
		d.logger.Error("createWriteRequest", "err", err)
		return err
	}

	d.logger.Debug("Influxdb request", "url", req.URL.String())

	res, err := d.dsInfo.HTTPClient.Do(req)
	if err != nil {
		d.logger.Error("HTTPClient Do", "err", err)
		return err
	}
	defer func() {
		if err := res.Body.Close(); err != nil {
			d.logger.Error("Failed to close response body", "err", err)
		}
	}()

	resbs, err := io.ReadAll(res.Body)
	if err != nil {
		return err
	}

	d.logger.Info("body result: ", string(resbs)) */

	return nil
}

func createDatabase(cli influxdbClientSDK.Client) error {
	q := influxdbClientSDK.Query{
		Command: "CREATE DATABASE test",
	}
	_, err := cli.Query(q)
	return err
}

func writeBySDK(cli influxdbClientSDK.Client, number int) error {
	pt, err := influxdbClientSDK.NewPoint(
		"obs_storage",
		map[string]string{"bucket": "grafana"},
		map[string]interface{}{"number": number},
		time.Now(),
	)
	if err != nil {
		return err
	}

	bp, err := influxdbClientSDK.NewBatchPoints(influxdbClientSDK.BatchPointsConfig{
		RetentionPolicy: "7d_events",
		Database:        "test",
		Precision:       "ns",
	})
	if err != nil {
		return err
	}

	bp.AddPoint(pt)

	// 写入数据到InfluxDB
	if err := cli.Write(bp); err != nil {
		return err
	}

	return nil
}

// TODO fix body
func createWriteRequest(ctx context.Context, dsInfo *influxdbModels.DatasourceInfo, queryStr string) (*http.Request, error) {
	u, err := url.Parse(dsInfo.URL)
	if err != nil {
		return nil, err
	}

	u.Path = path.Join(u.Path, "write")

	var req *http.Request
	req, err = http.NewRequestWithContext(ctx, http.MethodPost, u.String(), strings.NewReader(url.QueryEscape(queryStr)))
	if err != nil {
		return nil, err
	}

	req.Header.Set("Content-type", "application/x-www-form-urlencoded")

	params := req.URL.Query()
	params.Set("db", dsInfo.DbName)

	req.URL.RawQuery = params.Encode()

	return req, nil
}
